<?php
require_once('./includes/config.inc.php');
require_once('./lib/language.class.php');

class Msg {

    private $messages;

    public function __construct() {
        $this->SQL = MySQL::getInstance();
        $this->langMgr = new Language();

        $this->messages = array(
            //error messages
            'register-incomplete-error' => array('type' => 'error', 'message' => $this->langMgr->get('error_register_incomplete')),
            'register-email-error'      => array('type' => 'error', 'message' => $this->langMgr->get('error_register_email')),
            'register-exists-error'     => array('type' => 'error', 'message' => $this->langMgr->get('error_register_exists')),
            'user-update-error'         => array('type' => 'error', 'message' => $this->langMgr->get('error_user_update')),
            'add-location-error'        => array('type' => 'error', 'message' => $this->langMgr->get('error_add_location')),
            'add-route-error'           => array('type' => 'error', 'message' => $this->langMgr->get('error_add_route')),
            'checkin-error'             => array('type' => 'error', 'message' => $this->langMgr->get('error_checkin')),
            'checkin-exist-error'       => array('type' => 'error', 'message' => $this->langMgr->get('error_checkin_exists')),
            'edit-location-error'       => array('type' => 'error', 'message' => $this->langMgr->get('error_edit_location')),
            'edit-route-error'          => array('type' => 'error', 'message' => $this->langMgr->get('error_edit_route')),
            'feedback-error'            => array('type' => 'error', 'message' => $this->langMgr->get('error_feedback')),
            'search-short-error'        => array('type' => 'error', 'message' => $this->langMgr->get('error_search_short')),
            'password-reset-error'      => array('type' => 'error', 'message' => $this->langMgr->get('error_password_reset')),
            'user-exist-error'          => array('type' => 'error', 'message' => $this->langMgr->get('error_user_exist')),
            'login-error'               => array('type' => 'error', 'message' => $this->langMgr->get('error_login')),
            '404-error'                 => array('type' => 'error', 'message' => $this->langMgr->get('error_404'), 'noclose' => true),
            'password-change-error'     => array('type' => 'error', 'message' => $this->langMgr->get('error_password_change')),
            'password-match-error'      => array('type' => 'error', 'message' => $this->langMgr->get('error_password_match')),
            'password-old-error'        => array('type' => 'error', 'message' => $this->langMgr->get('error_password_old')),
            'password-reset-link-error' => array('type' => 'error', 'message' => $this->langMgr->get('error_password_reset_link')),
            'friend-follow-error'       => array('type' => 'error', 'message' => $this->langMgr->get('error_friend_follow')),
            'friend-unfollow-error'     => array('type' => 'error', 'message' => $this->langMgr->get('error_friend_unfollow')),
            'checkin-invalid-error'     => array('type' => 'error', 'message' => $this->langMgr->get('error_checkin_invalid')),
            'access-denied-error'       => array('type' => 'error', 'message' => $this->langMgr->get('error_access_denied')),
            'login-required-error'      => array('type' => 'error', 'message' => $this->langMgr->get('error_login_required')),
            'add-news-error'            => array('type' => 'error', 'message' => $this->langMgr->get('error_add_news')),

            //success messages
            'password-reset-success'    => array('type' => 'success', 'message' => $this->langMgr->get('success_password_reset')),
            'checkin-delete-success'    => array('type' => 'success', 'message' => $this->langMgr->get('success_checkin_delete')),
            'account-update-success'    => array('type' => 'success', 'message' => $this->langMgr->get('success_account_update')),
            'add-location-success'      => array('type' => 'success', 'message' => $this->langMgr->get('success_add_location')),
            'add-route-success'         => array('type' => 'success', 'message' => $this->langMgr->get('success_add_route')),
            'edit-location-success'     => array('type' => 'success', 'message' => $this->langMgr->get('success_edit_location')),
            'edit-route-success'        => array('type' => 'success', 'message' => $this->langMgr->get('success_edit_route')),
            'feedback-success'          => array('type' => 'success', 'message' => $this->langMgr->get('success_feedback')),
            'password-change-success'   => array('type' => 'success', 'message' => $this->langMgr->get('success_password_change')),
            'friend-follow-success'     => array('type' => 'success', 'message' => $this->langMgr->get('success_friend_follow')),
            'friend-unfollow-success'   => array('type' => 'success', 'message' => $this->langMgr->get('success_friend_unfollow')),
            'account-delete-success'    => array('type' => 'success', 'message' => $this->langMgr->get('success_account_delete')),
            'add-news-success'          => array('type' => 'success', 'message' => $this->langMgr->get('success_add_news')),

            'register-success'          => array('type' => 'success', 'message' => $this->langMgr->get('success_register'), 'noclose' => TRUE),

            //email templates
            'email-register'            => array(
                'type' => 'email',
                'subject' => $this->langMgr->get('email_subject_register'),
                'message' => $this->langMgr->get('email_body_register1') . $this->langMgr->get('email_body_register2')
            ),
            'email-follow'              => array(
                'type' => 'email',
                'subject' => $this->langMgr->get('email_subject_follow'),
                'message' => $this->langMgr->get('email_body_follow')
            ),
            'email-admin-register'      => array(
                'type' => 'email',
                'subject' => $this->langMgr->get('email_subject_admin_register'),
                'message' => $this->langMgr->get('email_body_admin_register')
            ),
            'email-passwordreset'       => array(
                'type' => 'email',
                'subject' => $this->langMgr->get('email_subject_passwordreset'),
                'message' => $this->langMgr->get('email_body_passwordreset')
            ),

            //error message to use when error message cannot be found
            'meta-error'                => array('type' => 'error', 'message' => 'Error message "{error}" not found!'),
        );
    }

    public function get($name, $replaces = array()) {
        if(isset($this->messages[$name])) {
            return $this->expandVariables($this->messages[$name], $replaces);
        } else {
            return $this->expandVariables($this->messages['meta-error'], array('{error}' => $name));
        }
    }

    public function formatMsg($error) {
        if($error) {
            $noclose = (isset($error['noclose']) && $error['noclose'] ? ' noclose' : '');
            return ($error ? '<div class="' . $error['type'] . $noclose . '">' . $error['message'] . '</div>' : '');
        } else {
            return '';
        }
    }

    private function expandVariables($message, $replaces) {
        $message['message'] = str_replace(array_keys($replaces), array_values($replaces), $message['message']);
        if(isset($message['subject'])) {
           $message['subject'] = str_replace(array_keys($replaces), array_values($replaces), $message['subject']);
        }
        return $message;
    }

    /*
     * sendPasswordResetMail - construct password reset email with reset link and send it
     * @param email string email address to send to
     * @return bool TRUE/FALSE depending on email send success
     */
    public function sendPasswordResetMail($email) {
        global $admin_email;
        $headers = array(
            'From: Vertigo <' . $admin_email . '>',
            'X-Mailer: PHP/' . phpversion(),
        );
        $user = $this->SQL->fetch_single('
            SELECT username
            FROM users
            WHERE username = "%s"
            LIMIT 1',
            $email
        );
        $replaces = array(
            '{host}'    => $_SERVER['HTTP_HOST'],
            '{hash}'    => sha1($user['username'] . PASSWORD_SALT),
        );
        $template = $this->get('email-passwordreset', $replaces);
        return @mail($email, $template['subject'], $template['message'], implode("\r\n", $headers));
    }

    /*
     * sendRegistrationMail - send email to user when new user registers
     * @param email string user email
     * @return bool TRUE/FALSE
     */
    public function sendRegistrationMail($email) {
        global $admin_email;
        $headers = array(
            'From: Vertigo <' . $admin_email . '>',
            'X-Mailer: PHP/' . phpversion(),
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=iso-8859-1',
        );
        $template = $this->get('email-register');
        return @mail($email, $template['subject'], $template['message'], implode("\r\n", $headers));
    }

    /*
     * sendAdminRegistrationMail - send email to admin when new user registers
     * @param data array user data of form (name, email)
     * @return bool TRUE/FALSE
     */
    public function sendAdminRegistrationMail($data) {
        global $admin_email;
        $headers = array(
            'From: Vertigo <' . $admin_email . '>',
            'X-Mailer: PHP/' . phpversion(),
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=iso-8859-1',
        );
        $replaces = array(
            '{name}'    => $data['name'],
            '{email}'   => $data['email'],
        );
        $template = $this->get('email-admin-register', $replaces);
        return @mail($admin_email, $template['subject'], $template['message'], implode("\r\n", $headers));
    }

    /*
     * sendFollowMail - send email to user when someone starts following him
     * @param user array user data of form (id, name, username)
     * @param follower array user data of form (id, name, username)
     * @return bool TRUE/FALSE
     */
    public function sendFollowMail($user, $follower) {
        global $admin_email;
        $headers = array(
            'From: Vertigo <' . $admin_email . '>',
            'X-Mailer: PHP/' . phpversion(),
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=iso-8859-1',
        );
        $replaces = array(
            '{follower_name}'   => $follower['name'],
            '{follower_id}'     => $follower['id'],
            '{user_name}'       => $user['name'],
        );
        $template = $this->get('email-follow', $replaces);
        //NB: a user's username is his/her email address
        return @mail($user['username'], $template['subject'], $template['message'], implode("\r\n", $headers));
    }
}
?>
